package com.example.XueCuApp.View.Xuechu;

import androidx.annotation.Nullable;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.device.PrinterManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.XueCuApp.Base.BaseActivity;
import com.example.XueCuApp.Base.BaseConfig;
import com.example.XueCuApp.Bean.HandSetCheckTicketRequsetBean;
import com.example.XueCuApp.Bean.HandSetCheckTicketResultBean;
import com.example.XueCuApp.Bean.JJHCheckResultBean;
import com.example.XueCuApp.Bean.JJHCheckResultOtherBean;
import com.example.XueCuApp.Bean.JJHCheckTicketBean;
import com.example.XueCuApp.Bean.JJHCheckTicketOtherBean;
import com.example.XueCuApp.Bean.JJHCheckTicketOtherSecondBean;
import com.example.XueCuApp.Bean.JJHXiaoPiaoDaYingBean;
import com.example.XueCuApp.Bean.QueryHandSetCheckTicketInfoRequestBean;
import com.example.XueCuApp.Bean.QueryHandSetCheckTicketInfoResultBean;
import com.example.XueCuApp.Bean.RepeatPrintCheckRecordRequsetBean;
import com.example.XueCuApp.Bean.RepeatPrintCheckRecordResultBean;
import com.example.XueCuApp.Customer.CheckResultem;
import com.example.XueCuApp.Customer.CheckTip;
import com.example.XueCuApp.Customer.SecondConfigDialog;
import com.example.XueCuApp.PrintHelp.PrintBillService;
import com.example.XueCuApp.R;
import com.example.XueCuApp.RetrufitHelp.BaseSubscriber;
import com.example.XueCuApp.RetrufitHelp.ExceptionHandle;
import com.example.XueCuApp.RetrufitHelp.RetrofitClient;
import com.example.XueCuApp.Utils.A9LReader;
import com.example.XueCuApp.Utils.IDCardInfo;
import com.example.XueCuApp.Utils.IDCardReader;
import com.example.XueCuApp.Utils.ListDataSave;
import com.example.XueCuApp.Utils.LogUtil;
import com.example.XueCuApp.Utils.SPUtil;
import com.example.XueCuApp.Utils.StringUtil;
import com.example.XueCuApp.Utils.TimeUtil;
import com.example.XueCuApp.Utils.ToastUtil;

import com.example.XueCuApp.Utils.util;
import com.example.XueCuApp.View.SettingActivity;
import com.example.XueCuApp.wight.CustomListShowWindow;
import com.example.XueCuApp.wight.NumberSubAddView;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;


public class NewXinZhongXinActivity extends BaseActivity {
    private CheckTip checkTip;
    private LinearLayout llPrepare;
    private LinearLayout llQuery;
    private LinearLayout llCheckResult;
    private LinearLayout llCheckShow;
    private TextView tvLinkBroken;
    private TextView tvTime;
    private TextView checkCount;
    private TextView ticketAgain;
    private RelativeLayout setting;
    private JJHCheckTicketBean jjhCheckTicketBean;
    private JJHCheckTicketOtherBean jjhCheckTicketOtherBean;
    private CustomListShowWindow bottomListWindow;
    private CheckResultem tickName;
    private CheckResultem tickNumber;
    private CheckResultem tickPersonNum;
    private CheckResultem tickPersonName;
    private CheckResultem tickTime;
    private CheckResultem tickMerction;
    private final int faceUp = 0;


    private String TAG = "NewXinZhongXinActivity";
    private static final int ReadScan = 0x11;

    //引入读取身份证，  新中心

    private boolean reading = false;
    private String status = "";
    private static final int UpDateTime = 0x04;
    boolean boolReadFringerprint = false;
    private static final int ReadOnceDone = 0x01;
    private boolean isReadingID = false;
    private boolean isReadingCard = false;
    private long timeNew;
    private long timeOld;
    private String OldID;


    //语音的引入
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    private String gateSoundName;


    //寻找卡类型

    private Timer timer;
    private final int cardAgain = 201;
    private QueryHandSetCheckTicketInfoRequestBean checkTicketInfoRequestBean;
    private Button btCheckNow;
    private Button btIdGet;
    private Button btPrint;

    private Message message;
    private Long mName;
    private String gateNo;

    private HandSetCheckTicketResultBean.DataBean printData;


    //扫二维码引入

    // 雪厨身份证引入
    private boolean gpiopower = false;
    private String sComPort;
    private int nBaud;
    private String sDeviceCodes;
    byte[] bt2 = new byte[96];
    IDCardReader id = null;

    //  打印
    private static final String[] mTempThresholdTable = {
            "80", "75", "70", "65", "60",
            "55", "50", "45", "40", "35",
            "30", "25", "20", "15", "10",
            "5", "0", "-5", "-10", "-15",
            "-20", "-25", "-30", "-35", "-40",
    };
    private final static int DEF_PRINTER_HUE_VALUE = 2;
    private int mPrinterSpeed = 9;
    private int mPrinterBlack = DEF_PRINTER_HUE_VALUE;

    private final static String PRNT_ACTION = "android.prnt.message";
    PrinterManager printer = new PrinterManager();
    private final static String SPINNER_PREFERENCES_FILE = "SprinterPrefs";
    private final static String SPINNER_SELECT_POSITION_KEY = "spinnerPositions";
    private final static int DEF_SPINNER_SELECT_POSITION = 6;
    private final static String SPINNER_SELECT_VAULE_KEY = "spinnerValue";
    private final static String DEF_SPINNER_SELECT_VAULE = mTempThresholdTable[DEF_SPINNER_SELECT_POSITION];

    private int mSpinnerSelectPosition;
    private String mSpinnerSelectValue;

    private CheckResultem orderBacthNumber;
    private CheckResultem orderSerialNumber;
    private CheckResultem orderTakePeople;
    private CheckResultem orderInTime;
    private CheckResultem orderBuyTicket;
    private CheckResultem orderCheckNumber;
    private HandSetCheckTicketRequsetBean checkTicketRequsetBean;

    //立即检票的数据 准备
    private QueryHandSetCheckTicketInfoResultBean.DataBean checkSelectData;
    private String checkNumber;
    private int checkCountSelect;
    private NumberSubAddView checkNumberSelect;

    private String orderCheckBatchNo;
    private RepeatPrintCheckRecordRequsetBean recordRequsetBean;
    private ListDataSave listDataSave;
    private List<JJHXiaoPiaoDaYingBean> xiaopiaoshuju;


    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {

                Log.i("zyf", "onInit: TTS引擎初始化成功");
            } else {
                Log.i("zyf", "onInit: TTS引擎初始化失败");
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case faceUp:
                    tvTime.setText(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_3));
                    mHandler.sendEmptyMessageDelayed(faceUp, 10000);
                    break;

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    // 返回 true  相同 小于  30 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 10) {
            System.out.println("zyf  未超过10秒 拒绝访问" + TimeUtil.getLocationTime());
//            PlayAudioFile("相同身份证30秒内拒绝二次检票");
            return true;
        } else {
            System.out.println("zyf  超过10秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }

    @Override
    protected void initView() {

        // 获取小票数据
        listDataSave = new ListDataSave(NewXinZhongXinActivity.this,"xiaopiao");

        xiaopiaoshuju = listDataSave.getDataList("xiaopiaoshuju",JJHXiaoPiaoDaYingBean.class);

        if (checkTicketInfoRequestBean == null) {
            checkTicketInfoRequestBean = new QueryHandSetCheckTicketInfoRequestBean();
        }

        if (checkTicketRequsetBean == null) {
            checkTicketRequsetBean = new HandSetCheckTicketRequsetBean();
        }

        if (recordRequsetBean == null) {
            recordRequsetBean = new RepeatPrintCheckRecordRequsetBean();
        }

        // 检票结果 标题显示
        checkTip = (CheckTip) findViewById(R.id.check_result_tip);
        btCheckNow = findViewById(R.id.bt_new_check_now);

        btIdGet = findViewById(R.id.bt_new_activity_id);
        btPrint = findViewById(R.id.bt_new_activity_print);

        tvTime = (TextView) findViewById(R.id.tv_time);
        checkCount = (TextView) findViewById(R.id.tv_check_count);
        ticketAgain = (TextView) findViewById(R.id.tv_new_xin_ticket_again);


        //检票结果显示
        tickName = (CheckResultem) findViewById(R.id.cr_ticket_name);
        tickNumber = (CheckResultem) findViewById(R.id.cr_ticket_number);
        tickPersonNum = (CheckResultem) findViewById(R.id.cr_ticket_person_number);
        tickPersonName = (CheckResultem) findViewById(R.id.cr_ticket_person_name);
        tickTime = (CheckResultem) findViewById(R.id.cr_ticket_time);
        tickMerction = (CheckResultem) findViewById(R.id.cr_ticket_merction);

        llCheckShow = (LinearLayout) findViewById(R.id.ll_result_show);

        //网络请求结果显示
        llCheckResult = (LinearLayout) findViewById(R.id.ll_check_result);

        // 请检票的页面
        llPrepare = (LinearLayout) findViewById(R.id.ll_prepare);
        //网络差的情况页面
        tvLinkBroken = (TextView) findViewById(R.id.tv_link_broken);

        //查询检票信息
        llQuery = (LinearLayout) findViewById(R.id.ll_check_query);
        //查询下的控件查找
        orderBacthNumber = findViewById(R.id.cr_ticket_order_number);
        orderSerialNumber = findViewById(R.id.cr_ticket_serial_number);
        orderTakePeople = findViewById(R.id.cr_ticket_take_people);
        orderInTime = findViewById(R.id.cr_ticket_in_time);
        orderBuyTicket = findViewById(R.id.cr_ticket_buy_ticket);
        orderCheckNumber = findViewById(R.id.cr_ticket_check_number);
        checkNumberSelect = findViewById(R.id.nsv_check_number_new);

        checkNumberSelect.setMaxValue(10);
        checkCountSelect = Integer.parseInt(checkNumberSelect.getValue());
        llPrepare.setVisibility(View.VISIBLE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.GONE);
        llQuery.setVisibility(View.GONE);


        setting = (RelativeLayout) findViewById(R.id.rl_fece_setting);

        if (jjhCheckTicketBean == null) {
            jjhCheckTicketBean = new JJHCheckTicketBean();
        }

        if (jjhCheckTicketOtherBean == null) {
            jjhCheckTicketOtherBean = new JJHCheckTicketOtherBean();
        }

        //获取TTS引擎
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }

        //终端名称
        mName = (Long) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_MEATION, 0L);
        cleanFace();
        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, "请检票！");
        tvTime.setText(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_3));
        String locationTimeNew = TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_TIME_EN_3);
        String dataToday = locationTimeNew.substring(8, 10);
        //根据日期 对 统计数据清零
        String data = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_DATA, "");
        if (!dataToday.equals(data)) {
            //如果日期不相等 那么就清零
            SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0);
            //给日期保存 更新日期
            SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_DATA, dataToday);
        }
        checkCount.setText((Integer) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0) + "");
        // 每隔1分钟就要去更新时间
        mHandler.sendEmptyMessageDelayed(faceUp, 10000);

        gateNo = (String) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_GATENO, "");

        checkNumberSelect.setOnAmountChangeListener(new NumberSubAddView.OnAmountChangeListener() {
            @Override
            public void onAmountChange(View view, int amount) {
                checkCountSelect = amount;
            }
        });

        //雪厨身份证模块 上电
        xueCuIdPerpar();
        xueCuIDPower();

        //获取到信息，然后去查询
//        queryHandSetCheckTicketInfo("340604199702282012");
    }

    private void xueCuIdPerpar() {
        write("base.dat");
        write("license.lic");
        initVar();
        initMainForm();

        if (sComPort.length() != 0 && nBaud != -1) {
            if (sDeviceCodes.equals("A9L")) {
                id = new A9LReader(this, sComPort, nBaud);
                Log.d(TAG, "  ------------- init A9LReader");
            } else
                ToastUtil.showToast("读卡器初始化错误，请重新选择设备型号。");
        }
    }

    private void xueCuIDPower() {


        if (id == null) return;
        gpiopower = id.PowerOnReader();
        Log.i(TAG, "++++++++++++++++++++++" + gpiopower);
        if (gpiopower) {
//            ToastUtil.showToast("读卡器上电完成。");
            ToastUtil.showToast("身份证模块初始化完成。");
        } else {
//            ToastUtil.showToast("读卡器初始化失败。");
            ToastUtil.showToast("身份证模块初始化失败。");
        }
    }

    private void queryHandSetCheckTicketInfo(String s) {
        checkTicketInfoRequestBean.setSearchData(s);
        RetrofitClient.getInstance(NewXinZhongXinActivity.this, BaseUrl, headers).queryHandSetCheckTicketInfo(checkTicketInfoRequestBean, new BaseSubscriber<QueryHandSetCheckTicketInfoResultBean>(NewXinZhongXinActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast(e.message);
                showFacesError();
                iosLoadDialog.dismiss();
                llPrepare.setVisibility(View.GONE);
                llCheckResult.setVisibility(View.GONE);
                tvLinkBroken.setVisibility(View.VISIBLE);
                llQuery.setVisibility(View.GONE);
                btIdGet.setVisibility(View.GONE);
            }

            @Override
            public void onNext(QueryHandSetCheckTicketInfoResultBean queryHandSetCheckTicketInfoResultBean) {
                iosLoadDialog.dismiss();
                if (queryHandSetCheckTicketInfoResultBean.getCode().equals("200")) {

                    //如果只有1条数据就直接显示，多条就选择显示
                    if (queryHandSetCheckTicketInfoResultBean.getData().size() <= 0) {
                        ToastUtil.showToast("该票查询到数据为空，请核实");
                    } else if (queryHandSetCheckTicketInfoResultBean.getData().size() == 1) {
                        btIdGet.setVisibility(View.GONE);
                        checkSelectData = queryHandSetCheckTicketInfoResultBean.getData().get(0);
                        showSelectFace(queryHandSetCheckTicketInfoResultBean.getData().get(0));
                    } else {
                        showBottomList(queryHandSetCheckTicketInfoResultBean.getData());
                    }
                } else {
                    ToastUtil.showToast(queryHandSetCheckTicketInfoResultBean.getMessage());
                }

            }
        });
    }

    private void showBottomList(final List<QueryHandSetCheckTicketInfoResultBean.DataBean> data) {
        bottomListWindow = new CustomListShowWindow(NewXinZhongXinActivity.this, data, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                // 根据所选数据  进行页面显示
                btIdGet.setVisibility(View.GONE);
                showSelectFace(data.get(position));
                checkSelectData = data.get(position);
                bottomListWindow.dismiss();
            }
        });

        bottomListWindow.showAtLocation(llCheckResult, Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, 0);

        bottomListWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bottomListWindow.backgroundAlpha(NewXinZhongXinActivity.this, 1f);
            }
        });
    }

    private void showSelectFace(QueryHandSetCheckTicketInfoResultBean.DataBean dataBean) {
        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.GONE);
        llQuery.setVisibility(View.VISIBLE);

        orderBacthNumber.setResultText(dataBean.getOrderBatchNO());
        orderSerialNumber.setResultText(dataBean.getOrderSerialNumber());
        orderTakePeople.setResultText(dataBean.getTackOrderName());
        orderInTime.setResultText(dataBean.getValidStartDT().substring(0, 10) + "至" + dataBean.getValidEndDT().substring(0, 10));
        orderBuyTicket.setResultText(dataBean.getEnableCheckNum() + "/" + dataBean.getProductNum());
        orderCheckNumber.setResultText("(最大张数10)");
    }

    private void showCheckAladyResult(HandSetCheckTicketResultBean.DataBean data) {

        checkTip.SetIcoBg(R.mipmap.tip);
        checkTip.SetText(R.color.yellow_title, "已经检票");
        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.VISIBLE);
        tvLinkBroken.setVisibility(View.GONE);
        llQuery.setVisibility(View.GONE);

        tickName.setVisibility(View.VISIBLE);
        tickNumber.setVisibility(View.VISIBLE);
        tickPersonNum.setVisibility(View.VISIBLE);
        tickPersonName.setVisibility(View.VISIBLE);
        tickTime.setVisibility(View.VISIBLE);
        tickMerction.setVisibility(View.VISIBLE);

        tickName.setResultText(data.getProductName());
        tickNumber.setResultText(data.getTicketValidTimes());
        tickPersonNum.setResultText(data.getPassPersonSum() + "");
        tickPersonName.setResultText(data.getCertificateName());
        tickTime.setResultText(data.getCheckTime());
        tickMerction.setResultText(data.getTerminalName());
    }

    private void showCheckOtherResult(HandSetCheckTicketResultBean data) {

        checkTip.SetIcoBg(R.mipmap.tip);
        checkTip.SetText(R.color.yellow_title, data.getMessage());
        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.VISIBLE);
        tvLinkBroken.setVisibility(View.GONE);
        llQuery.setVisibility(View.GONE);

        tickName.setVisibility(View.GONE);
        tickNumber.setVisibility(View.GONE);
        tickPersonNum.setVisibility(View.GONE);
        tickPersonName.setVisibility(View.GONE);
        tickTime.setVisibility(View.GONE);
        tickMerction.setVisibility(View.GONE);

        tickName.setResultText("");
        tickNumber.setResultText("");
        tickPersonNum.setResultText("");
        tickPersonName.setResultText("");
        tickTime.setResultText("");
        tickMerction.setResultText("");

    }


    private void showCheckSuccessResult(HandSetCheckTicketResultBean.DataBean data) {
        orderCheckBatchNo = data.getOrderCheckBatchNo();
        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, "检票成功");
        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.VISIBLE);
        tvLinkBroken.setVisibility(View.GONE);
        llQuery.setVisibility(View.GONE);

        tickName.setVisibility(View.VISIBLE);
        tickNumber.setVisibility(View.VISIBLE);
        tickPersonNum.setVisibility(View.VISIBLE);
        tickPersonName.setVisibility(View.VISIBLE);
        tickTime.setVisibility(View.VISIBLE);
//        tickMerction.setVisibility(View.VISIBLE);

        tickName.setResultText(data.getProductName());
        tickNumber.setResultText(data.getTicketValidTimes());
        tickPersonNum.setResultText(data.getPassPersonSum() + "");
        tickPersonName.setResultText(data.getCertificateName());
        tickTime.setResultText(data.getCheckTime());
//        tickMerction.setResultText(data.getProductName());
        vitalCount(data.getPassPersonSum());

        //检票成功 就 询问是否打印
        btPrint.setVisibility(View.VISIBLE);
    }


    private final BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        public void onReceive(android.content.Context context, android.content.Intent intent) {
            String tiaoMa = new String(intent.getByteArrayExtra("barocode"), 0, intent.getIntExtra("length", 0));
            checkTip.SetIcoBg(R.mipmap.pass);
            checkTip.SetText(R.color.green, "请检票！");
            checkNumber = tiaoMa;
//            llPrepare.setVisibility(View.GONE);
//            llCheckResult.setVisibility(View.GONE);
//            tvLinkBroken.setVisibility(View.GONE);
//            llQuery.setVisibility(View.VISIBLE);
            iosLoadDialog.show();
            queryHandSetCheckTicketInfo(checkNumber);
            PlayAudioFile("请稍等");
//            ToastUtil.showToast(tiaoMa);

        }
    };

    @Override
    protected void initData() {

        //二维码检票  扫
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                RepeatPrintCheckRecordResultBean print = new RepeatPrintCheckRecordResultBean();
//                print.setData(new RepeatPrintCheckRecordResultBean.DataBean());
//                RepeatPrintCheckRecordResultBean.DataBean dataBean = print.getData();
//
//
//                dataBean.setGuideName("测试");
//                dataBean.setOrderCheckBatchNo("测试");
//                dataBean.setGuideCertificateName("测试");
//                dataBean.setGuideCertificateNo("测试");
//                dataBean.setGuidePhone("测试");
//                dataBean.setBusinessOrgShortName("测试");
//                dataBean.setProductName("测试");
//                dataBean.setProductNum(0);
//                dataBean.setSalePrice(0);
//                dataBean.setProductNum(0);
//                dataBean.setSalePriceSum(0);
//                dataBean.setPaymentTypeName("测试");
//                dataBean.setTerminalName("测试");
//                dataBean.setCheckTime("测试");
//
//
//                printPaper(dataBean);

            }
        });

        //小票重打
        ticketAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewXinZhongXinActivity.this, TicketPrintAgainActivity.class));
            }
        });

        //立即检票
        btCheckNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                queryHandSetCheckTicketInfo("110101199003078777");
//                printPaper(CfgStr);
                //查询到票结果，去检票
                goToCheck();
            }
        });

        btIdGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkTip.SetIcoBg(R.mipmap.pass);
                checkTip.SetText(R.color.green, "请检票！");
                PlayAudioFile("请稍等");
                clickGetIdNumber();
            }
        });

        btPrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打印票信息
                getPrintDate(orderCheckBatchNo);

                if (btPrint.getVisibility() == View.VISIBLE) {
                    btPrint.setVisibility(View.GONE);
                }
            }
        });

    }

    private void getPrintDate(String orderCheck) {
        recordRequsetBean.setOrderCheckBatchNo(orderCheck);
        RetrofitClient.getInstance(NewXinZhongXinActivity.this, BaseUrl, headers).repeatPrintCheckRecord(recordRequsetBean, new BaseSubscriber<RepeatPrintCheckRecordResultBean>(NewXinZhongXinActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast(e.message);
            }

            @Override
            public void onNext(RepeatPrintCheckRecordResultBean repeatPrintCheckRecordResultBean) {
                if (repeatPrintCheckRecordResultBean.getCode().equals("200")) {
                    if (repeatPrintCheckRecordResultBean.getData() != null) {
                        printPaper(repeatPrintCheckRecordResultBean.getData());
                    }else {
                        ToastUtil.showToast("打印数据对象为空");
                    }
                } else {
                    ToastUtil.showToast(repeatPrintCheckRecordResultBean.getMessage());
                }

            }
        });
    }

    private void clickGetIdNumber() {

        Log.d(TAG, "cccccccccccc读文字图像信息开始＋＋＋＋＋＋＋＋＋");
        if (id == null) return;
        AlertDialog.Builder builder = new AlertDialog.Builder(NewXinZhongXinActivity.this);

        builder.setTitle("读文字图像信息");
        Log.d(TAG, "读文字图像信息");
        if (!gpiopower) {
            ttsMessageBox("设备未上电，请重新上电");
            return;
        }
        if (id.InitReader(bt2)) {
            String[] s = new String[1];
            IDCardInfo info = id.ReadBaseCardInfo(s);
            Log.d(TAG, "读文字图像信息111");
            if (info != null) {
                String sInfo = "姓名：" + info.getName() + "\n"
                        + "证件号码：" + info.getCardNum() + "\n"
                        + "性别：" + info.getGender() + "\n"
                        + "民族：" + info.getNation() + "\n"
                        + "生日：" + info.getBirthday() + "\n"
                        + "签发机关：" + info.getRegistInstitution() + "\n"
                        + "有效期：" + info.getValidStartDate() + "-" + info.getValidEndDate() + "\n";

                if (info.getAddress() != null && info.getAddress().length() > 0)
                    sInfo += "最新地址：" + info.getAddress() + "\n";

                if (info.getFingerInfo() != null) {
                    sInfo += "指纹：证件中含有指纹信息\n";
                    ttsMessageBox("读取成功，证件中含有指纹信息");
                } else {
//                    ttsMessageBox("读取成功" + "身份证号：" + info.getCardNum());
                    //身份证 读取成功 去做请求
                    iosLoadDialog.show();
                    checkNumber = "110101199003075154";
                    queryHandSetCheckTicketInfo("110101199003075154");
//                    queryHandSetCheckTicketInfo(info.getCardNum());
                }
                Log.d(TAG, "cccccccccccc图片");
                sInfo += "头像：\n";
                builder.setMessage(sInfo);
                String filePath = Environment.getExternalStorageDirectory()
                        .getAbsolutePath() + "/wltlib";
                FileInputStream fis;
                Bitmap bmp = null;
                try {
                    fis = new FileInputStream(filePath
                            + "/zp.bmp");
                    bmp = BitmapFactory.decodeStream(fis);


                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                    }
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Log.d(TAG, "cccccccccccc图片－－－－－－－－－－－");
                if (bmp == null) {
//                    builder.show();
//                    Toast.makeText(getApplicationContext(), "头像不存在！", Toast.LENGTH_SHORT).show();
                } else {
                    ImageView imgView3 = new ImageView(this);
                    imgView3.setImageBitmap(bmp);
                    imgView3.setMaxHeight(126);
                    imgView3.setMaxWidth(102);
                    builder.setView(imgView3);
//                    builder.show();
                }

                Log.d(TAG, "cccccccccccc读文字图像信息结束－－－－－－－－－－－");
            } else {
                ttsMessageBox("读卡失败，请重新放证");
            }
        } else ToastUtil.showToast("读卡器初始化失败。");

    }

    private void ttsMessageBox(String msg) {
        ToastUtil.showToast(msg);
        PlayAudioFile(msg);

    }


    // 雪厨 立即去检票  checkSelectData
    private void goToCheck() {
        if (StringUtil.isNullOrEmpty(gateNo)) {
            ToastUtil.showToast("闸机编号未绑定，请确认绑定信息");
            return;
        }
        checkTicketRequsetBean.setSearchData(checkNumber);
        checkTicketRequsetBean.setOrderId(checkSelectData.getOrderId());
        checkTicketRequsetBean.setGateNo(gateNo);
        checkTicketRequsetBean.setCheckCount(checkCountSelect);
//        List<HandSetCheckTicketRequsetBean.OrderCertificateListBean> listCheck = new ArrayList<>();
//        for (int i = 0; i < checkSelectData.getCertificateList().size(); i++) {
//            HandSetCheckTicketRequsetBean.OrderCertificateListBean orderCertificateListBean = new HandSetCheckTicketRequsetBean.OrderCertificateListBean();
//            orderCertificateListBean.setOrderCertificateId(checkSelectData.getCertificateList().get(i).getOrderCertificateId());
//            listCheck.add(orderCertificateListBean);
//        }
//        checkTicketRequsetBean.setOrderCertificateList(listCheck);
        RetrofitClient.getInstance(NewXinZhongXinActivity.this, BaseUrl, headers).handSetCheckTicket(checkTicketRequsetBean, new BaseSubscriber<HandSetCheckTicketResultBean>(NewXinZhongXinActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast(e.message);
                btIdGet.setVisibility(View.VISIBLE);
                showFacesError();
            }

            @Override
            public void onNext(HandSetCheckTicketResultBean handSetCheckTicketResultBean) {
                btIdGet.setVisibility(View.VISIBLE);
                if (handSetCheckTicketResultBean.getCode().equals("0")) {
                    //检票成功 是否需要打印呢 不过先正常显示一下
                    showCheckSuccessResult(handSetCheckTicketResultBean.getData());
                    PlayAudioFile(handSetCheckTicketResultBean.getMessage());

                    // 路过检票成功，那么就保存数据

                    JJHXiaoPiaoDaYingBean jjhXiaoPiaoDaYingBean = new JJHXiaoPiaoDaYingBean();

                    jjhXiaoPiaoDaYingBean.setOrderNo(handSetCheckTicketResultBean.getData().getOrderNo());
                    jjhXiaoPiaoDaYingBean.setCheckTime(handSetCheckTicketResultBean.getData().getCheckTime());
                    jjhXiaoPiaoDaYingBean.setPassPersonSum(handSetCheckTicketResultBean.getData().getPassPersonSum() + "");
                    jjhXiaoPiaoDaYingBean.setOrderCheckBatchNo(handSetCheckTicketResultBean.getData().getOrderCheckBatchNo());
                    if (xiaopiaoshuju.size() < 5) {
                        xiaopiaoshuju.add(jjhXiaoPiaoDaYingBean);
                    } else if (xiaopiaoshuju.size() >= 5) {
                        xiaopiaoshuju.remove(0);
                        xiaopiaoshuju.add(jjhXiaoPiaoDaYingBean);
                    }
                    listDataSave.setDataList("xiaopiaoshuju",xiaopiaoshuju);
                } else if (handSetCheckTicketResultBean.getCode().equals("300002")) {
                    //已检票显示
                    showCheckAladyResult(handSetCheckTicketResultBean.getData());
                    PlayAudioFile(handSetCheckTicketResultBean.getMessage());
                } else {
                    showCheckOtherResult(handSetCheckTicketResultBean);
                    PlayAudioFile(handSetCheckTicketResultBean.getMessage());
                    ToastUtil.showToast(handSetCheckTicketResultBean.getMessage());
                }

            }
        });

    }


    @Override
    public int initLayoutId() {
        return R.layout.activity_new_xin_zhong_xin;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == BaseConfig.QROK) {
            if (requestCode == BaseConfig.QRBUNDLE) {

            }
        }

        if (resultCode == RESULT_OK) {
            switch (requestCode) {

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.d("onResume");

        IntentFilter filter = new IntentFilter();
        filter.addAction(PRNT_ACTION);
        registerReceiver(mPrtReceiver, filter);

        IntentFilter filter1 = new IntentFilter();
        filter1.addAction("urovo.rcv.message");
        registerReceiver(mScanReceiver, filter1);


        readSpinnerPrefsState(this);

    }

    // read prefs to restore
    private boolean readSpinnerPrefsState(Context c) {
        SharedPreferences sharedPrefs = c.getSharedPreferences(SPINNER_PREFERENCES_FILE, MODE_PRIVATE);
        mSpinnerSelectPosition = sharedPrefs.getInt(SPINNER_SELECT_POSITION_KEY, DEF_SPINNER_SELECT_POSITION);
        mSpinnerSelectValue = sharedPrefs.getString(SPINNER_SELECT_VAULE_KEY, DEF_SPINNER_SELECT_VAULE);

        return (sharedPrefs.contains(SPINNER_SELECT_POSITION_KEY));
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.d("onRestart");

    }

    private BroadcastReceiver mPrtReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            int ret = intent.getIntExtra("ret", 0);
            if (ret == -1)
                Toast.makeText(NewXinZhongXinActivity.this, R.string.bt_print_no_paper, Toast.LENGTH_SHORT).show();
        }
    };


    private void showFacesError() {
        checkTip.SetIcoBg(R.mipmap.error);
        checkTip.SetText(R.color.red_self, "检票失败");
        PlayAudioFile("未获取到数据，请检查网络");
        tickName.setVisibility(View.GONE);
        tickNumber.setVisibility(View.GONE);
        tickPersonNum.setVisibility(View.GONE);
        tickPersonName.setVisibility(View.GONE);
        tickTime.setVisibility(View.GONE);
        tickMerction.setVisibility(View.GONE);

        iosLoadDialog.dismiss();
        llPrepare.setVisibility(View.GONE);
        llCheckResult.setVisibility(View.GONE);
        tvLinkBroken.setVisibility(View.VISIBLE);
        llQuery.setVisibility(View.GONE);

        btIdGet.setVisibility(View.GONE);
    }


    private void vitalCount(int number) {
        int count = (Integer) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0);
        count = count + number;
        checkCount.setText(count + "");
        SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, count);
    }

    private void vitalCountOther(JJHCheckResultOtherBean jjhCheckResultBean) {
        int count = (Integer) SPUtil.get(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, 0);
        count = count + jjhCheckResultBean.getData().getPassPersonSum();
        checkCount.setText(count + "");
        SPUtil.put(NewXinZhongXinActivity.this, BaseConfig.JJH_CHECK_COUNT, count);
    }

    private void cleanFace() {

        checkTip.SetIcoBg(R.mipmap.pass);
        checkTip.SetText(R.color.green, "请检票");

        tickName.setResultText("");
        tickPersonNum.setResultText("");
        tickPersonName.setResultText("");
        tickTime.setResultText("");
        tickMerction.setResultText("");

        tickName.setVisibility(View.GONE);
        tickNumber.setVisibility(View.GONE);
        tickPersonNum.setVisibility(View.GONE);
        tickPersonName.setVisibility(View.GONE);
        tickTime.setVisibility(View.GONE);
        tickMerction.setVisibility(View.GONE);
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        if (mSpeech == null) {
            mSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        }
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i("zyf", "中文设置失败");
        } else {
            Log.i("zyf", "中文设置成功");
        }
        mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
    }

//    public void printPaper(String print) {
//
//        Intent intentService = new Intent(this, PrintBillService.class);
//        intentService.putExtra("SPRT", print);
//        startService(intentService);
//    }

    public void printPaper(RepeatPrintCheckRecordResultBean.DataBean print) {

        Intent intentService = new Intent(this, PrintBillService.class);
        intentService.putExtra("SPRT", print);
        startService(intentService);
    }

    // write prefs to file for restroing
    private boolean writeSpinnerPrefsState(Context c) {
        SharedPreferences sharedPrefs = c.getSharedPreferences(SPINNER_PREFERENCES_FILE, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPrefs.edit();

        editor.putInt(SPINNER_SELECT_POSITION_KEY, mSpinnerSelectPosition);
        editor.putString(SPINNER_SELECT_VAULE_KEY, mSpinnerSelectValue);

        return (editor.commit());
    }

    @Override
    protected void onStop() {
        super.onStop();


    }

    @Override
    protected void onPause() {
        super.onPause();


        unregisterReceiver(mPrtReceiver);
        writeSpinnerPrefsState(this);

        unregisterReceiver(mScanReceiver);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LogUtil.d("页面要被销毁了，请保存数据");
    }

    private void write(String myfile) {
        InputStream inputStream;
        String filePath = Environment.getExternalStorageDirectory() + "/wltlib";
        if (isExist(filePath + "/" + myfile)) return;
        try {
            inputStream = NewXinZhongXinActivity.this.getResources().getAssets().open(myfile);
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(filePath + "/" + myfile);
            byte[] buffer = new byte[512];
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, count);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
            System.out.println("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isExist(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    private void initMainForm() {

        String[] sRet = new String[1];

    }

    private void initVar() {
        //设置读卡器参数
        String Version = Build.VERSION.RELEASE;
        if (Version.equals("4.3") || Version.equals("8.1.0"))
            sComPort = "/dev/ttyHSL0";///dev/ttyUSB0
        else
            sComPort = "/dev/ttyHSL1";
        sDeviceCodes = "A9L";//A9L
        String sBaud = "115200";//115200
        nBaud = Integer.decode(sBaud);

    }


}
